package com.cdwm.mrp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cdwm.mrp.common.tools.JwtHelper;
import com.cdwm.mrp.common.tools.ResultCode;
import com.cdwm.mrp.common.tools.ResultVO;
import com.cdwm.mrp.domain.po.User;
import com.cdwm.mrp.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @version v1.0
 * @Author: lyw
 * @Date: 2021/8/3
 */
@Api(tags = "登录管理")
@Controller
@Slf4j
public class LoginController {


    @Autowired
    private UserService userService;


    @ApiOperation("登录授权")
    @PostMapping("/auth/loginToken")
    @ResponseBody
    public ResultVO<?> loginToken(User user) {
        System.out.println("==============================");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        queryWrapper.lambda().eq(User::getUsername,user.getUsername())
                .eq(User::getPassword,new BCryptPasswordEncoder().encode(user.getPassword()));
        User userOne = userService.getOne(queryWrapper);

        if (userOne != null){
            return ResultVO.ok(JwtHelper.createToken(userOne.getId(),userOne.getUsername()));
        }

        return ResultVO.fail(ResultCode.USERNAME_PASSWORD_ERROR);
    }
}
